(function(E, KIT, RES) {
  "use strict";
  var __URL_ROOT = RES.URL_ROOT + "/life";
  var __URL_ROOT_EXAM = RES.URL_ROOT + "/lifecycexample";

  var __AXIS = null;
  var __PATHS = [];

  rapid.Page.create({
    render: {
      titleBar: "生命周期",
      header: E.form({id: "frmSearch"}),
      main: E.grid("grd"),
      other: E.block(
        E.window("wndAxis",
          E.div({id: "axis"})
        ),
        E.window("wndPer",
          E.grid("grdExampleNodePER"),
          E("input").attr("type", "hidden").attr("id", "hdnPer")
        ),
        E.window("wndFil",
          E.grid("grdFil"),
          E("input").attr("type", "hidden").attr("id", "hdnFil")
        ),
        E.window("wndUpload",
          E("input").attr("id", "pkUpload"),
          E.div({id: "dynamicFile"})
        )
      )
    },
    methods: {
      _initForm: function() {
        var __app = this;

        rapid("#frmSearch").dataview({
          colSize: 0,
          padding: false,
          fields: [{
            editor: {
              name: "title", tip: "请输入标题..."
            }
          }, {
            editor: {
              tip: "请选择企业名称...",
              name: "company",
              type: "picker",
              editable: true,
              dataSource: {
                textField: "enterprise_name",
                valueField: "conflict_id",
                url: __URL_ROOT_EXAM + "/getEnterpriseName"
              },
              autocomplete: {
                paramName: "search_name",
                dataSource: {
                  textField: "enterprise_name",
                  valueField: "conflict_id",
                  url: __URL_ROOT_EXAM + "/getEnterpriseName"
                }
              }
            }
          },/* {
            editor: {
              tip: "请选择会议类型...",
              name: "meettype",
              type: "picker",
              editable: false,
              dataSource: {
                textField: "codename",
                valueField: "customid",
                url: __URL_ROOT_EXAM + "/getMeetType"
              }
            }
          }, */{
            template: function() {
              return E.view({cssClass: "r-nowrap"},
                E.button({
                  id: "btnSearch", icon: "fa-search", text: "搜索"
                })
              );
            }
          }],
          oninit: function() {
            rapid.ui("#btnSearch").on("click", function() {
              var __search_params = rapid("#frmSearch").dataview().serializeJson();
              __search_params.code = __app.location().params.code;
              __search_params.ismodel = __app.location().params.ismodel;

              rapid("#grd").grid().tag("searchparams", __search_params).load({
                data: __search_params
              });
            });
          }
        });
      },
      _initWnd: function() {
        var __app = this;

        rapid("#wndAxis").window({
          title: "时光轴",
          size: "max",
          onShow: function() {
            console.log(rapid("#grd").grid().current().ui().attrib_01.val());
            __app._renderAxis(rapid("#grd").grid().current().ui().attrib_01.val(),
              rapid("#grd").grid().current().ui().conflict_id.val());
          },
          onHide: function() {
            __app._destoryAxis();
          }
        });

        rapid("#wndFil").window({
          title: "附件管理",
          height: 500,
          size: "xl",
          onShow: function() {
            var nodeid = $("#hdnFil").val();

            rapid("#grdFil").grid().load({
              data: {
                nodeid: nodeid
              }
            });
          },
          onHide: function() {
            rapid("#grdFil").grid().clear();
            $("#hdnFil").val("");
            __AXIS.refresh();
          }
        });

        rapid("#wndUpload").window({
          title: "附件上传",
          width: 350,
          maxHeight: 550,
          onShow: function() {
            var nodeid = $("#hdnFil").val();

            rapid("#pkUpload").picker().dataSource({
              data: "nodeid=" + nodeid
            });
          },
          onHide: function() {
            $("#dynamicFile").g_webuploader().clearHtml();
            rapid("#pkUpload").picker().val("");
          }
        });

        rapid("#wndPer").window({
          title: "下一节点人员设置",
          size: "lg",
          height: 500,
          onShow: function() {
            var nodeid = $("#hdnPer").val();

            rapid("#grdExampleNodePER").grid().load({
              data: "row_id=" + nodeid
            });
          },
          onHide: function() {
            rapid("#grdExampleNodePER").grid().clear();
            $("#hdnPer").val("");
            __AXIS.refresh();
          }
        });
      },
      _initGrid: function() {
        var __app = this;

        rapid("#grd")
          .grid({
            height: "100%",
            dataSource: {
              url: __URL_ROOT + "/getLives"
            },
            pageable: true,
            keyFields: "conflict_id",
            paramFields: ["conflict_id", "attrib_01", "attrib_03"],
            fields: [{
              title: "标题", width: 250, action: function(item) {
                return this.action({id: "timeline", text: item.attrib_01});
              }
            }, {
              title: "企业名称", name: "attrib_05_cn", width: 200
            }, /*{
              title: "会议类型", name: "meet_type", width: 100
            }, {
              title: "有效截止日期", name: "attrib_14", width: 100,
              formatter: "date:yyyy-MM-dd"
            }, */{
              title: "状态", name: "attrib_15", width: 100, align: "center",
              formatter: function(value, text, css) {
                css.color = value == 1 ? null : 6;
                return value == 1 ? "启用" : "禁用";
              }
            }, {
              title: "下载附件", width: 100, align: "center", action: function(item, css) {
                return "<a href= '" + __URL_ROOT + "/batchZip?id=" + item.conflict_id + "'><i class='fas fa-download'></i></a>";
              }
            }, {
              title: "描述", name: "attrib_19", width: 400
            }],
            singleActions: __app._getGridSingeActions_()
          });

        rapid("#grdFil")
          .grid({
            height: function() {
              return rapid("#wndFil").window().height() - 5;
            },
            dataSource: {
              url: __URL_ROOT + "/getLifeFils"
            },
            actions: [],
            removable: true,
            pageable: true,
            keyFields: "conflict_id",
            paramFields: ["attrib_01", "attrib_12"],
            fields: [{
              title: "下载", width: 50, align: "center", action: function(item, css) {
                return "<a href= '" + __URL_ROOT + "/download?path=" + item.attrib_12 + "'><i class='fas fa-download'></i></a>";
              }
            }, {
              title: "附件类型", name: "attrib_01_cn", width: 150
            }, {
              title: "附件名称", name: "attrib_02", width: 350
            }]
          })
          .on("remove", function(ids) {
            if(rapid.isEmpty(ids)) {
              rapid.warn("至少选择一条数据");
              return false;
            }

            var __grid = this;

            var nodeid = $("#hdnFil").val();

            __app._getLifeLimit(nodeid, function() {
              rapid.post({
                url: __URL_ROOT + "/deleteFils",
                data: "ids=" + ids,
                success: function() {
                  rapid("#grdFil").grid().reload();
                }
              });
            });
          });

        /**
         * 
         * @type {{pageable: boolean, addable: boolean, detailed: boolean, keyFields: string, removable: boolean, editMode: string, updatable: boolean, paramFields: string[], window: {size: string}, fields: *[], dataSource: {url: string}, dataview: {colSize: number}, height: (function(): *)}}
         * @private
         */
        var _gridOption = {

          height: function() {
            return rapid("#wndPer").window().height();
          },
          addable: true,
          updatable: true,
          removable: true,
          detailed: true,
          editMode: "popup",
          dataSource: {
            url: __URL_ROOT_EXAM + "/getExampleNodePER"
          },
          pageable: true,
          keyFields: "conflict_id",
          paramFields: ["conflict_id", "row_id"],
          dataview: {
            colSize: 1
          },
          window: {
            size: "sm"
          },
          fields: [
            {
              title: "人员", name: "attrib_01_cn", width: 150, editor: {
                name: "attrib_01",
                type: "picker",
                tip: "请选择...",
                multiple: true,
                autoReload: true,
                editable: true,
                textField: "attrib_01_cn",
                dataSource: {
                  textField: "name",
                  valueField: "id",
                  url: __URL_ROOT_EXAM + "/getUsers"
                },
                autocomplete: {
                  paramName: "search_name",
                  dataSource: {
                    textField: "name",
                    valueField: "id",
                    url: __URL_ROOT_EXAM + "/getUsers"
                  }
                },
                validator: {
                  rules: {
                    required: true
                  }
                }
              }
            },
            {
              title: "类型", name: "attrib_02_cn", width: 150,
              editor: {
                name: "attrib_02",
                type: "picker",
                textField: "attrib_02_cn",
                tip: "请选择...",
                dataSource: {
                  textField: "codename",
                  valueField: "customid",
                  url: __URL_ROOT_EXAM + "/getUserType"
                },
                validator: {
                  rules: {
                    required: true
                  }
                }
              }
            }
          ]
        };

        rapid("#grdExampleNodePER")
          .grid(_gridOption)
          .on("add", function(e) {
            var __row_id = $("#hdnPer").val();
            var __grid = this;
            rapid.confirm("确定要保存吗？", function(yes) {
              if(yes) {
                rapid.post({
                  url: __URL_ROOT_EXAM + "/saveLifecycExamplePER",
                  data: $.extend(true, {}, e.serializeJson(), {row_id: __row_id}),
                  success: function(result) {
                    e.hide();

                    rapid.success("保存成功。", function() {
                      __grid.reload();
                    }, false);
                  }
                });
              }
            });
          })
          .on("update", function(e) {
            var __row_id = $("#hdnPer").val();
            var __grid = this;
            rapid.confirm("确定要保存吗？", function(yes) {
              if(yes) {
                rapid.post({
                  url: __URL_ROOT_EXAM + "/saveLifecycExamplePER",
                  data: $.extend(true, {}, e.serializeJson(), {row_id: __row_id}),
                  success: function(result) {
                    e.hide();

                    rapid.success("保存成功。", function() {
                      __grid.reload();
                    }, false);
                  }
                });
              }
            });
          })
          .on("remove", function(ids) {
            var __grid = this;
            rapid.post({
              url: __URL_ROOT_EXAM + "/deleteExamplePER",
              data: "ids=" + ids,
              success: function() {
                __grid.reload();
              }
            });
          });
      },

      _getGridSingeActions_: function() {
        var __app = this;

        return [{
          "时光轴": function() {
            rapid("#wndAxis").window().show();
          }
        }, {
          "下载附件": function() {
            var id = rapid("#grd").grid().current().ui().conflict_id.val();

            __app._batchZip(id);
          }
        }]
      },
      _initAxis: function() {
        var axis = new Axis({
          id: "axis",
          title: "",
          source: {
            dynamic: {
              url: __URL_ROOT + "/getLifeNodes"
            }
          },
          content: {
            top: function(item, index) {
              return item.attrib_01;
            },
            middle: function(item, index) {
              return item.attrib_20;
            },
            bottom: {
              left: function(item, index) {
                var html = (rapid.isEmpty(item.attrib_14) ? "" : ("<span>截止：" + rapid.date.format(item.attrib_14, "yyyy-MM-dd") + "</span>"));
                html += (rapid.isEmpty(item.fjlx) ? "" : "<span>必传附件类型：<i style='color: #ff0000;'>" + item.fjlx + "</i></span>");

                return html;
              },
              right: function(item, index) {
                var btns = [];

                if(!rapid.isEmpty(item.frmcodes) && item.frmcodes.length > 0) {
                  for(var i = 0; i < item.frmcodes.length; i++) {
                    var frmcode = item.frmcodes[i];
                    var frmname = item.frmnames[i];
                    var frmnum = item.frmnums[i];

                    btns.push(
                      E.div(
                        E.button({
                          text: frmname + "(" + frmnum + ")",
                          color: 3,
                          size: "sm"
                        }).attr({
                          "data-code": frmcode,
                          "data-name": frmname,
                          "data-nodeid": item.conflict_id
                        }).addClass("fn-form-btn", "r-hlg")
                      ).addClass("d-btn")
                    );
                  }
                }

                if(!rapid.isEmpty(item.uploadnum) && item.uploadnum > 0) {
                  btns.push(
                    E.div(
                      E.button({
                        text: "附件资料(" + item.filnum + ")",
                        color: 4,
                        size: "sm"
                      }).attr({
                        "data-nodeid": item.conflict_id
                      }).addClass("fn-upload-btn", "r-hlg")
                    ).addClass("d-btn")
                  );
                }

                if(!rapid.isEmpty(item.preuploadnum) && item.preuploadnum > 0) {
                  btns.push(
                    E.div(
                      E.button({
                        text: "上节点附件(" + item.prefilnum + ")",
                        color: 2,
                        size: "sm"
                      }).attr({
                        "data-nodeid": item.conflict_id,
                        "data-prenodeid": item.prenodeid
                      }).addClass("fn-download-btn", "r-hlg")
                    ).addClass("d-btn")
                  );
                }

                if(!rapid.isEmpty(item.nextset) && item.nextset == "1") {
                  btns.push(
                    E.div(
                      E.button({
                        text: "设置下一节点人员",
                        color: 1,
                        size: "sm"
                      }).attr({
                        "data-nodeid": item.conflict_id,
                        "data-nextnodeid": item.nextnodeid
                      }).addClass("fn-per-btn", "r-hlg")
                    ).addClass("d-btn")
                  );
                }

                return btns.join("");
              }
            }
          }
        });

        return axis;
      },
      _renderAxis: function(name, id) {
        var __app = this;

        if(rapid.isEmpty(__AXIS)) {
          __AXIS = __app._initAxis();
        }

        __AXIS.settings({
          title: name,
          source: {
            dynamic: {
              params: {
                id: id
              }
            }
          }
        }).render();
      },
      _destoryAxis: function() {
        if(!rapid.isEmpty(__AXIS)) {
          __AXIS.destory();
        }
      },
      _initBtn: function() {
        var __app = this;

        rapid("#grd").grid().on("timeline", function() {
          rapid("#wndAxis").window().show();
        });

        $("#axis").on("click", ".fn-form-btn", function() {
          var $this = $(this);

          var code = $this.data("code");
          var name = $this.data("name");
          var keyid = $this.data("nodeid");

          __app._getLifePer(keyid, function() {
            rapid.navigateTo(RES.URL_ROOT + "/formdata/index?title=" + name + "&code=" + code + "&keyid=" + keyid, {
              onHide: function() {
                __AXIS.refresh();
              }
            }, false);
          });
        });

        $("#axis").on("click", ".fn-upload-btn", function() {
          var nodeid = $(this).data("nodeid");

          if(rapid.isEmpty(nodeid)) {
            rapid.warn("未查询到任何数据");
            return false;
          }

          __app._getLifePer(nodeid, function() {
            $("#hdnFil").val(nodeid);

            rapid("#grdFil").grid({
              actions: [{
                text: "附件上传",
                icon: "fa-upload",
                toolbar: true,
                handler: function() {
                  var nodeid = $("#hdnFil").val();

                  __app._getLifeLimit(nodeid, function() {
                    rapid("#wndUpload").window().show();
                  });
                }
              }],
              removable: true
            });

            rapid("#wndFil").window().show();
          });
        });

        $("#axis").on("click", ".fn-download-btn", function() {
          var nodeid = $(this).data("nodeid");
          var prenodeid = $(this).data("prenodeid");

          if(rapid.isEmpty(prenodeid)) {
            rapid.warn("未查询到任何数据");
            return false;
          }

          __app._getLifePer(nodeid, function() {
            $("#hdnFil").val(prenodeid);

            rapid("#grdFil").grid({
              actions: [],
              removable: false
            });

            rapid("#wndFil").window().show();
          });
        });

        $("#axis").on("click", ".fn-per-btn", function() {
          var nodeid = $(this).data("nodeid");
          var nextnodeid = $(this).data("nextnodeid");

          if(rapid.isEmpty(nextnodeid)) {
            rapid.warn("未查询到任何数据");
            return false;
          }

          __app._getLifePer(nodeid, function() {
            $("#hdnPer").val(nextnodeid);

            rapid("#wndPer").window().show();
          });
        });
      },
      _initPicker: function() {
        rapid("#pkUpload").picker({
          cssClass: "picker",
          dataSource: {
            textField: "attrib_01_cn",
            valueField: "attrib_01",
            url: __URL_ROOT + "/getAccTypes"
          },
          validator: {
            rules: {
              required: true
            }
          }
        });
      },
      _initWebUploader: function() {
        $("#dynamicFile").g_webuploader({
          uploadType: "file",
          multiple: true,
          fileNumLimit: 10,
          threads: 5,
          server: __URL_ROOT + "/upload",
          onUploadBefore: function() {
            if(!rapid("#pkUpload").picker().valid()) {
              return false;
            }

            return true;
          },
          onUploadSuccess: function(file, response) {
            if(rapid.isUndefined(response)) {
              rapid.warning("系统异常，请刷新。");
              return false;
            }

            if(response.state == 1) {
              if(!rapid.isEmpty(response.message)) {
                rapid.success(response.message);
              }

              if(__PATHS.indexOf(response.data) == -1) {
                __PATHS.push(response.data);
              }
            } else {
              if(!rapid.isEmpty(response) && !rapid.isEmpty(response.message)) {
                rapid.warning(response.message);
              }
            }
          },
          onUploadFinished: function() {
            var nodeid = $("#hdnFil").val();
            var type = rapid("#pkUpload").picker().val();
            var paths = __PATHS.join(",");

            if(!rapid.isEmpty(paths)) {
              //将路径存入数据库
              rapid.ajax({
                url: __URL_ROOT + "/saveFils",
                data: {
                  nodeid: nodeid,
                  type: type,
                  paths: paths
                },
                success: function() {
                  rapid.success("上传成功");
                }
              });

              __PATHS = [];
              rapid("#grdFil").grid().reload();
              rapid("#wndUpload").window().hide();
            }
          }
        });
      },
      _getLifePer: function(nodeid, cb) {
        rapid.ajax({
          url: __URL_ROOT + "/getLifePer",
          async: false,
          responseMsg: false,
          data: {
            nodeid: nodeid
          },
          success: function(rs, msg) {
            typeof cb == "function" && cb();
          },
          fail: function(rs, msg) {
            rapid.fail(msg);
          }
        });
      },
      _getLifeLimit: function(nodeid, cb) {
        rapid.ajax({
          url: __URL_ROOT + "/getLifeLimit",
          async: false,
          responseMsg: false,
          data: {
            nodeid: nodeid
          },
          success: function(rs, msg) {
            typeof cb == "function" && cb();
          },
          fail: function(rs, msg) {
            rapid.fail(msg);
          }
        });
      },
      _batchZip: function(id) {
        rapid.post({
          url: __URL_ROOT + "/batchZip",
          data: "id=" + id,
          success: function(rs) {
            window.open(rs);
          },
          fail: function(rs, msg) {
            rapid.error(msg);
          }
        });
      }
    }
  })(function() {
    this._initForm();
    this._initWnd();
    this._initGrid();
    this._initBtn();
    this._initPicker();
    this._initWebUploader();

    var __params = this.location().params;

    rapid("#grd").grid().load({
      data: {
        code: __params.code,
        ismodel: __params.ismodel
      }
    });
  }).init();
})
(rapid.html.Element, rapid.kit, rapid.res);